# -*- coding: UTF-8 -*-
# @Create   : 2021/5/11 11:06 上午
# @Author   : yh
# @Remark   : 权限装饰器，用于权限校验
import functools


def is_write(module_id: str, sub_module_id: str):
    """
    判断登陆账户是否是可写此页面
    :param module_id: 模块id
    :param sub_module_id: 页面id
    """
    import json

    def fun_wrapper(fun):
        @functools.wraps(fun)
        def wrapper(self):
            if not hasattr(self, "session"):
                return self.mx_error("请登录")
            get_info = GetUserInfo(self.session)
            if get_info.state:
                return self.mx_error("请登录")
            self.company = get_info.company
            self.user_id = get_info.user_id

            db = TreeModel()
            try:
                group = db.open('Co', 'Co_1\\UG\\BSUser\\' + self.user_id, file='master').fetchone_value(
                    'BSUserAndGroupRelations')
            except AssertionError:
                return self.mx_error('数据库错误：' + self.user_id + '无法获取BSUserAndGroupRelations属性！')
            if group == 'BSUserGroup.1':
                return fun(self)
            g = GETPersonnelGroup('Co_1')
            g.get_parent_key(group)
            try:
                group_module = json.loads(
                    db.open('Co', 'Co_1\\UG\\' + g.create_path(), file='master').fetchone_value('GroupModul'))
            except (AssertionError, UnicodeError):
                return self.mx_error('获取用户组权限失败')

            for module in group_module:
                if module.get('id') == module_id:
                    for sub_module in module.get('SubModul'):
                        if sub_module.get('id') == sub_module_id and sub_module.get('write') == 1:
                            return fun(self)
            return self.mx_error('权限不足')

        return wrapper

    return fun_wrapper
